package com.runtime.hongyunmanage.controller;

import com.runtime.hongyunmanage.bean.*;
import com.runtime.hongyunmanage.service.CategoryService;
import com.runtime.hongyunmanage.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/products")
@CrossOrigin(origins = "http://localhost:8001") // 允许前端跨域
public class ProductController {

    @Autowired
    private ProductService productService;
    private CategoryService  categoryService;



    // 获取商品列表（支持搜索）
    @PostMapping
    public Result findProducts(@RequestBody ProductQuery query){

        Integer currentPage = query.getCurrentPage();
        Integer pageSize = query.getPageSize();
        String keyword = query.getKeyword();
        Products products = new Products();


        int offset = (currentPage - 1) * pageSize;
        if (keyword != null && !keyword.isEmpty()) {
            // 判断是否为productNumber格式（假设为纯数字+字母）
            if (keyword.matches("^[0-9]+$")) {
                products.setProductNumber(keyword);
            } else {
                // 否则认为是productName
                products.setProductName(keyword);
            }
        }

        Map<String, Object> map = productService.findProductsByCondition(pageSize, offset, products);
        // 从map中获取列表数据
        List<Products> list = (List<Products>) map.get("list");
// 从map中获取总数
        Integer totals = (Integer) map.get("totals");
        Integer code= null != list && list.size()> 0 ? Code.GET_OK : Code.GET_ERR;
        String msg = null != list && list.size() > 0 ? "查询用户列表成功" : "查询用户列表失败";
        return new Result(code,map,msg);
    }


    //表单目录回显
    @GetMapping("/category")
    public Result getCategoryList(@RequestParam(required = false) Long parentId,
                                  @RequestParam(required = false) String keyword) {
        List<Categories> list = categoryService.getCategoryList(parentId, keyword);
        Integer code = null != list && list.size() > 0 ? Code.GET_OK : Code.GET_ERR;
        String msg = null != list && list.size() > 0 ? "查询商品目录列表成功" : "查询商品目录列表失败";
        return new Result(code, list, msg);
    }


    // 商品上架/下架
    @PutMapping("/{productId}/publish")
    public Result togglePublish(@PathVariable Integer productId, @RequestParam Integer isPublished) {
        if (isPublished == 1) {
            productService.publishProduct(productId);
        } else {
            productService.unpublishProduct(productId);
        }
        return new Result(Code.UPDATE_OK, null, "状态更新成功");
    }
    // 新增商品
    @PostMapping("/add")
    public Result add(@RequestBody ProductRequest request) {

        productService.addProduct(request.getProduct(), request.getDetails(), request.getImages());
        return new Result(Code.SAVE_OK, null, "新增成功");
    }

    // 编辑商品（基础信息+详细信息）
    @PutMapping("/{productId}")
    public Result update(@PathVariable Integer productId, @RequestBody ProductRequest request) {

        productService.updateProduct(productId.longValue(), request);
        // 如需更新详细信息，可从form中提取description/specifications/images等字段并调用对应的Service方法
        return new Result(Code.UPDATE_OK, null, "更新成功");
    }

    // 删除商品
    @DeleteMapping("/{productId}")
    public Result delete(@PathVariable Integer productId) {
        productService.deleteProduct(productId);
        return new Result(Code.DELETE_OK, null, "删除成功");
    }

    // 按ID查询商品
    @GetMapping("/{productId}")
    public Result getById(@PathVariable Integer productId) {
        Products product = productService.findProductById(productId);
        return new Result(product != null ? Code.GET_OK : Code.GET_ERR, product, "查询结果");
    }

    // 库存预警（测试接口）
    @GetMapping("/check-stock-alert")
    public void checkStockAlert() {
        productService.checkStockAlert();
    }
}